#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工具函数模块
"""

import os
import time
import socket
import platform
import hashlib


def generate_agent_id():
    """生成基于本机信息的Agent ID"""
    try:
        # 获取主机名
        hostname = socket.gethostname()
        
        # 获取本机IP地址
        local_ip = "127.0.0.1"
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            s.close()
        except:
            pass
        
        # 格式化IP地址
        ip_formatted = local_ip.replace('.', '_')
        agent_id = "agent_{}_ip_{}".format(hostname, ip_formatted)
        
        return agent_id
        
    except Exception as e:
        return 'agent_{}'.format(int(time.time()))


def load_env_file():
    """手动加载.env文件"""
    try:
        with open('.env', 'r') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    os.environ[key.strip()] = value.strip()
        print("手动加载.env文件成功")
        return True
    except FileNotFoundError:
        print(".env文件不存在")
        return False
    except Exception as e:
        print("加载.env文件失败:", e)
        return False


def execute_job_function(job_data):
    """根据job数据中的fun_name动态调用对应的方法"""
    import sys
    
    fun_name = job_data.get('fun_name')
    if not fun_name:
        return {
            'status': 'error',
            'message': '任务数据中缺少fun_name字段'
        }
    
    # 获取当前模块
    current_module = sys.modules[__name__]
    
    # 检查方法是否存在
    if not hasattr(current_module, fun_name):
        return {
            'status': 'error',
            'message': '方法 {} 在 tools.py 中不存在'.format(fun_name)
        }
    
    try:
        # 获取方法并调用
        func = getattr(current_module, fun_name)
        result = func(job_data)
        return result
        
    except Exception as e:
        return {
            'status': 'error',
            'message': '调用方法 {} 时发生错误: {}'.format(fun_name, str(e))
        }


def fun_telnet(job_data):
    """telnet测试方法"""
    import socket
    
    try:
        url = job_data.get('url')
        port = int(job_data.get('port', 23))
        
        # 创建socket连接测试
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(10)  # 10秒超时
        
        result = sock.connect_ex((url, port))
        sock.close()
        
        if result == 0:
            return {
                'status': 'success',
                'message': 'telnet连接成功',
                'url': url,
                'port': port
            }
        else:
            return {
                'status': 'failed',
                'message': 'telnet连接失败',
                'url': url,
                'port': port,
                'error_code': result
            }
            
    except Exception as e:
        return {
            'status': 'error',
            'message': 'telnet测试异常: {}'.format(str(e)),
            'url': job_data.get('url'),
            'port': job_data.get('port')
        }


def fun_curl(job_data):
    """curl测试方法"""
    import requests
    
    try:
        url = job_data.get('url')
        if not url:
            return {
                'status': 'error',
                'message': '任务数据中缺少url字段'
            }
        
        # 如果URL没有协议前缀，默认添加http://
        if not url.startswith(('http://', 'https://')):
            url = 'http://' + url
        
        # 发送HTTP请求，设置超时时间
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            return {
                'status': 'success',
                'message': 'curl请求成功',
                'url': url,
                'status_code': response.status_code,
                'response_time': response.elapsed.total_seconds()
            }
        else:
            return {
                'status': 'failed',
                'message': 'curl请求失败',
                'url': url,
                'status_code': response.status_code,
                'response_time': response.elapsed.total_seconds()
            }
            
    except requests.exceptions.Timeout:
        return {
            'status': 'failed',
            'message': 'curl请求超时',
            'url': job_data.get('url')
        }
    except requests.exceptions.ConnectionError:
        return {
            'status': 'failed',
            'message': 'curl连接失败',
            'url': job_data.get('url')
        }
    except Exception as e:
        return {
            'status': 'error',
            'message': 'curl测试异常: {}'.format(str(e)),
            'url': job_data.get('url')
        }


def get_system_info():
    """获取系统CPU、内存、磁盘信息"""
    import psutil
    
    try:
        # CPU信息
        cpu_percent = psutil.cpu_percent(interval=1)
        cpu_count = psutil.cpu_count()
        load_avg = psutil.getloadavg() if hasattr(psutil, 'getloadavg') else (0, 0, 0)
        
        # 内存信息
        memory = psutil.virtual_memory()
        memory_total = round(memory.total / (1024**3), 2)  # GB
        memory_used = round(memory.used / (1024**3), 2)   # GB
        memory_percent = memory.percent
        
        # 磁盘信息
        disk = psutil.disk_usage('/')
        disk_total = round(disk.total / (1024**3), 2)     # GB
        disk_used = round(disk.used / (1024**3), 2)       # GB
        disk_percent = round((disk.used / disk.total) * 100, 2)
        
        system_info = {
            'cpu_usage_percent': cpu_percent,
            'cpu_core_count': cpu_count,
            'cpu_load_avg_1m': load_avg[0],
            'cpu_load_avg_5m': load_avg[1],
            'cpu_load_avg_15m': load_avg[2],
            'memory_total_gb': memory_total,
            'memory_used_gb': memory_used,
            'memory_usage_percent': memory_percent,
            'disk_total_gb': disk_total,
            'disk_used_gb': disk_used,
            'disk_usage_percent': disk_percent
        }
        
        return system_info
        
    except ImportError:
        # 如果没有psutil，使用基础方法获取信息
        return get_basic_system_info()
    except Exception as e:
        print("获取系统信息失败:", e)
        return None


def get_basic_system_info():
    """基础系统信息获取（不依赖psutil）"""
    import subprocess
    import platform
    
    try:
        system_info = {
            'cpu_usage_percent': 0,
            'cpu_core_count': os.cpu_count() or 1,
            'cpu_load_avg_1m': 0,
            'cpu_load_avg_5m': 0,
            'cpu_load_avg_15m': 0,
            'memory_total_gb': 0,
            'memory_used_gb': 0,
            'memory_usage_percent': 0,
            'disk_total_gb': 0,
            'disk_used_gb': 0,
            'disk_usage_percent': 0,
            'platform': platform.system()
        }
        
        # 尝试获取基本信息
        if platform.system() == 'Darwin':  # macOS
            try:
                # 获取内存信息
                result = subprocess.run(['vm_stat'], capture_output=True, text=True)
                if result.returncode == 0:
                    # 简单解析vm_stat输出
                    pass
            except:
                pass
        
        return system_info
        
    except Exception as e:
        print("获取基础系统信息失败:", e)
        return None